<?php

class JobController extends Controller
{
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='//layouts/column1';
    

	/**
	 * @return array action filters
	 */
	public function filters()
	{
		return array(
				'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view','create','viewType','searchJob', 'searchAdvanceJob','ajaxDropDown','ajaxCurrency'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('update'),
				'users'=>array('@'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('admin'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

    /**
     * Average money bided to this project
     * return VNĐ
     */
    protected function averageMoney($jobid) {
        $bids = Bidjob::model()->findAllByAttributes(array('job_id'=>$jobid));
        $sum = 0;
        $count = 0;
        foreach ($bids as $bid) {
            if ($bid->currency == 'USD')
                $sum += $bid->money*20000; // asuming 1 USD = 20000 VNĐ
            else
                $sum += $bid->money;
            $count ++; 
        }
        return ($count==0) ? 0 : $sum/$count;
    } 

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
	    $model = $this->loadModel($id);
	    $comment = $this->createComment($model);
	    $userUp = Users::model()->findByAttributes(array('id'=>$model->user_id));
        $countBid = Bidjob::model()->countByAttributes(array('job_id'=>$id));
        $averageMoney = $this->averageMoney($id);
		// nhung viec lam da duoc  BID
		$bid = Job::model()->findByAttributes(array('id'=>$id, 'status'=>2));
		
		// so luot xem cua du an
        $visit =Job::model()->findByPk($id);
        $visit->updateCounters(
            array('viewed'=>1),"id={$id}"   
        );
		
		$this->render('view',array(
				'model'=>$model, 'userUp'=>$userUp->username,
                'countBid'=>$countBid, 'averageMoney'=>$averageMoney,
				'comment' => $comment,
				'bid' => $bid,
				'visit'=>$visit,
		));
	}
	
	
	
	protected function createComment($issue) {
		$comment = new Comment;
		if (isset($_POST['Comment'])) {
			$comment->attributes = $_POST['Comment'];
			if ($issue->addComment($comment)) {
				Yii::app()->user->setFlash('commentSubmitted', "Your comment has been added.");
				$this->refresh();
			}
		}
		return $comment;
	}
    /**
     * Display jobtype
     */
    public function actionViewType($id) {
        $jobtype = SubJobtype::model()->findByAttributes(array('id'=>$id));
        $this->render('viewType', array(
            'list'=>$jobtype,
        ));
    }
	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
     
     
     public function actionAjaxDropDown(){
        $data=SubJobtype::model()->findAll('jobtype_id=:jobtype_id', 
                  array(':jobtype_id'=>(int) $_POST['jobtype_id']));
 
        $data=CHtml::listData($data,'id','name');
        foreach($data as $value=>$name)
        {
                echo CHtml::tag('option',
                           array('value'=>$value),CHtml::encode($name),true);
        }
     }
     
     public function actionAjaxCurrency(){
        $data=Budget::model()->findAll('currency=:currency', 
                  array(':currency'=>(string) $_POST['currency']));
 
        $data=CHtml::listData($data,'id','money');
        foreach($data as $value=>$name)
        {
                echo CHtml::tag('option',
                           array('value'=>$value),CHtml::encode($name),true);
        }
     }
     
public function actionCreate()
	{
		ob_start();

		$model=new Job;
		$login = new LoginForm();
		$user = new Users();

		// Uncomment the following line if AJAX validation is needed
		$this->performAjaxValidation($model);


		if(isset($_POST['Job']))
		{
            $checkLogin = 0;
            $checkUsers = 0;
			$model->attributes=$_POST['Job'];
            if (isset($_POST['LoginForm'])){   
                if ( ($_POST['LoginForm']["username"] == "") && ($_POST['LoginForm']["password"] == "") ){
                    $checkLogin =1;
                }   
            }
            if ( isset($_POST['Users']) ){
                
                if (($_POST['Users']["email"] == "" ) && ( $_POST['Users']["name"] == " " )  && ($_POST['Users']["username"] == "") 
                    &&  ($_POST['Users']["password"] == "" ) && ( $_POST['Users']["password_repeat"] == "") ){
                        $checkUsers  = 1;
                }   
            }
            if ($checkLogin == 0 && $checkUsers == 0){
                Yii::app()->user->setFlash('error1', "Bạn đã chọn cả hai phần đã có người dùng và thêm người dùng");
            }
            if (isset( $_POST['Users']) && $checkLogin == 1 ){
                $username = $_POST['Users']['username'];
				$pass = $_POST['Users']['password'];
				$user->setCheckCaptcha(false);// kiem tra de xu ly k dung captcha
				$user->attributes=$_POST['Users'];
				if($user->save()){
					$model->setUserid($user->id);	
					$user_id = $user->id;
					$userprofiles = UserProfiles::model()->findByAttributes(array('user_id'=>$user_id));
					if(!isset($userprofiles->user_id)) {
						// an SQL with two placeholders ":username" and ":email"
						$sql="INSERT INTO tbl_user_profiles (user_id, display_name) VALUES(:user_id, :display_name)";	
						$command = Yii::app()->db->createCommand($sql);
						// replace the placeholder ":username" with the actual username value
						$command->bindParam(":user_id",$user_id,PDO::PARAM_INT);
						// replace the placeholder ":email" with the actual email value
						$command->bindParam(":display_name",$username,PDO::PARAM_STR);		
						$command->execute();
					}
					
                    $model->subjobtype_id = $_POST['subjobtype_id'];
					if($model->save()){
                        if ($_POST['Job']["fileattached"] != ""){
       	                   $path = Yii::getPathOfAlias('webroot') . '/data/fileattached/';
					       $model->fileattached = CUploadedFile::getInstance($model, 'fileattached');
					       $model->fileattached->saveAs($path . $model->fileattached);				        
				        }
						$identity=new UserIdentity($username,$pass);
						if ($identity->authenticate()== UserIdentity::ERROR_NONE ){
							Yii::app()->user->login($identity);
							$this->redirect(array('view','id'=>$model->id));
						}
					}
				}
            }else if ( isset($_POST['LoginForm']) && $checkUsers == 1){
                $username = $_POST['LoginForm']["username"];
				$pass = $_POST['LoginForm']["password"];
				$identity=new UserIdentity($username,$pass);	
				
				if ($identity->authenticate() == UserIdentity::ERROR_NONE){
					$sql = Yii::app()->db->createCommand("select * from tbl_users where username = '".$username."'" )->queryRow();
					$model->setUserid($sql["id"]);
                    $model->subjobtype_id = $_POST['subjobtype_id'];
					if ($model->save()){
					   if ($_POST['Job']["fileattached"] != ""){
       	                   $path = Yii::getPathOfAlias('webroot') . '/data/fileattached/';
					       $model->fileattached = CUploadedFile::getInstance($model, 'fileattached');
					       $model->fileattached->saveAs($path . $model->fileattached);				        
				        }
						Yii::app()->user->login($identity);
						//$login->login($username);
						$this->redirect(array('view','id'=>$model->id));
					}
                }
            }else{
				$model->setUserid(Yii::app()->user->id);
                $model->subjobtype_id = $_POST['subjobtype_id'];
                //echo $_POST['subjobtype_id'].'aaaaaaaaaaaaaaaaaaaa'.$model->subjobtype_id;
				if ($model->save()){
				    if ($_POST['Job']["fileattached"] != ""){
       	                   $path = Yii::getPathOfAlias('webroot') . '/data/fileattached/';
					       $model->fileattached = CUploadedFile::getInstance($model, 'fileattached');
					       $model->fileattached->saveAs($path . $model->fileattached);				        
				    }
                    echo $_POST['subjobtype_id'].'aaaaaaaaaaaaaaaaaaaa';
					$this->redirect(array('view','id'=>$model->id));
				}
			}
		}


		$this->render('create',array(
				'model'=>$model,
				'user' => $user,
				'login' => $login,
		));
		ob_end_flush();
	}
	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Job']))
		{
			$model->attributes=$_POST['Job'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
				'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
		/*
		$dataProvider=new CActiveDataProvider('Job');
		$this->render('index',array(
				'dataProvider'=>$dataProvider,
		));
		*/
		$post = new Job();
		$criteria = new CDbCriteria();
		$page = new CPagination();
		$page->setItemCount(Job::model()->count($criteria));
		$page->setPageSize(15);
		$page->applyLimit($criteria);
		$model = Job::model()->findAll($criteria);
		$this->render('index', array('page'=>$page,'post'=>$post,'model'=>$model));
	}
    
    public function actionSearchAdvanceJob() {
        $model = new Job('searchAdvanceJob');
		$model->unsetAttributes();  // clear any default values
		if (isset($_GET['Job'])) {
			$model->attributes = $_GET['Job'];
			$this->render('searchAdvanceJob', array('model'=>$model));
		}
    }
	public function actionSearchJob() {
        $model = new Job('searchJob');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Job'])) {
            $model->attributes = $_GET['Job'];
            $this->render('searchJob', array('model'=>$model));
        }
    }

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Job('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Job']))
			$model->attributes=$_GET['Job'];

		$this->render('admin',array(
				'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Job::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='job-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
	
}
